//
//  PurchaseCarViewController.m
//  PalmChangtu
//
//  Created by shaorui on 15/6/14.
//  Copyright (c) 2015年 PalmChangtu. All rights reserved.
//

#import "PurchaseCarViewController.h"
#import "SettlementViewController.h"
#import "ShareUserModel.h"
#import "MyCustomCell.h"

#import "CommentViewController.h"
#import "commentsCell.h"
#import "BaseUrlConfig.h"
#import "BannerCell.h"
#import "ShareUserModel.h"
#import "MainTabbarController.h"
#import "JSONKit.h"
#import "Common.h"
#import "LoadingView.h"
#import "NetWarningView.h"
#import "AFNetworking.h"
#import "BaseUrlConfig.h"
#import "UIImageView+AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "all_commodity_TypeModel.h"
#import "localJSONModel.h"
#import "MTLJSONAdapter.h"
#import "GetRemandModle.h"
#import "ShangPinListModel.h"
#import "PurchaseCarModel.h"


@interface PurchaseCarViewController ()
{

    float allPrice;
    float alTotallPrice;
    NSMutableArray *infoArr;
    NSInteger currentNum;
    NSInteger pageNum;
    
    BOOL request;

}



@end

@implementation PurchaseCarViewController
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
    }
    return self;
}

-(void)viewDidAppear:(BOOL)animated
{
    
    if (request) {
        request = NO;
    }
    [self getShoppingCartActionRequest];
    [self totalPrice];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    infoArr = [[NSMutableArray alloc] init];
    
    request = YES;
    
    
    currentNum =0;
    pageNum = 10;

//getShoppingCartAction
        //设置标题的属性样式等
    
        //初始化数据
    allPrice = 0.0;
    infoArr = [[NSMutableArray alloc]init];
    /**
     *  初始化一个数组，数组里面放字典。字典里面放的是单元格需要展示的数据
     */
//    for (int i = 0; i<7; i++)
//        {
//        NSMutableDictionary *infoDict = [[NSMutableDictionary alloc]init];
//        [infoDict setValue:@"img6.png" forKey:@"imageName"];
//        [infoDict setValue:@"这是商品标题" forKey:@"goodsTitle"];
//        [infoDict setValue:@"2000" forKey:@"goodsPrice"];
//        [infoDict setValue:[NSNumber numberWithBool:NO] forKey:@"selectState"];
//        [infoDict setValue:[NSNumber numberWithInt:1] forKey:@"goodsNum"];
//        
//            //封装数据模型
//        PurchaseCarModel *goodsModel = [[PurchaseCarModel alloc]initWithDict:infoDict];
//        
//            //将数据模型放入数组中
//        [infoArr addObject:goodsModel];
//        
//        
//        }
    
    /**
     创建表格，并设置代理
     */
        //    TableView
        //user nib
    UINib *nibCell = [UINib nibWithNibName:NSStringFromClass([MyCustomCell class]) bundle:nil];
    [self.MyTableView registerNib:nibCell forCellReuseIdentifier:[NSString stringWithFormat:@"%@", [MyCustomCell class]]];
    self.MyTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    

    _MyTableView.dataSource = self;
    _MyTableView.delegate = self;
    
        //给表格添加一个尾部视图
    

    
        //添加全选图片按钮
    [_btnDelete removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    [_btnDelete addTarget:self action:@selector(btnDeleteClick:) forControlEvents:UIControlEventTouchUpInside];



    [_allSelectBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [_allSelectBtn removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    [_allSelectBtn addTarget:self action:@selector(selectBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [_btnSettlement removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    [_btnSettlement addTarget:self action:@selector(btnSettlementAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
        //添加一个结算按钮
    [self.settlementBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.settlementBtn.backgroundColor = [UIColor blueColor];
    [_v_Top.lalTitel setText:@"购物车"];
    [_v_Top.btnGoback setHidden:YES];
    _v_Top.parentController = self.navigationController;

    _arrModelData  = [[NSMutableArray alloc] init];


}

/**
 *  创建表格尾部视图
 *
 *  @return 返回一个UIView 对象视图，作为表格尾部视图
 */

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 1;
}

    //返回单元格个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return infoArr.count;
}
    //定制单元格内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier =  @"MyCustomCell";
    MyCustomCell * Cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    Cell.selectionStyle  = UITableViewCellSelectionStyleNone;
//    [Cell initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    Cell.delegate = self;


        //调用方法，给单元格赋值
    [Cell addTheValue:infoArr[indexPath.row]];
    
    
    return Cell;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @" 删除 ";
}
    //返回单元格的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}

    //单元格选中事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    /**
     *  判断当期是否为选中状态，如果选中状态点击则更改成未选中，如果未选中点击则更改成选中状态
     */
    PurchaseCarModel *model = infoArr[indexPath.row];
    
    if (model.selectState)
        {
            model.selectState = NO;

        }
    else
        {
                model.selectState = YES;


        }

        //刷新整个表格
        //    [_MyTableView reloadData];
    
        //刷新当前行
    [_MyTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    
    [self totalPrice];
}

/**
 *  全选按钮事件
 *
 *  @param sender 全选按钮
 */
-(void)selectBtnClick:(UIButton *)sender
{
        //判断是否选中，是改成否，否改成是，改变图片状态
    sender.tag = !sender.tag;
    if (sender.tag)
        {
        [sender setImage:[UIImage imageNamed:@"check_choise"] forState:UIControlStateNormal];
        
        }else{
            [sender setImage:[UIImage imageNamed:@"check_unchoise"] forState:UIControlStateNormal];
        }
        //改变单元格选中状态
    for (int i=0; i<infoArr.count; i++)
        {
        PurchaseCarModel *model = [infoArr objectAtIndex:i];
        model.selectState = sender.tag;
        }
        //计算价格
    [self totalPrice];
        //刷新表格
    [_MyTableView reloadData];
    
}

#pragma mark -- 实现加减按钮点击代理事件
/**
 *  实现加减按钮点击代理事件
 *
 *  @param cell 当前单元格
 *  @param flag 按钮标识，11 为减按钮，12为加按钮
 */
-(void)btnClick:(UITableViewCell *)cell andFlag:(int)flag
{
    NSIndexPath *index = [_MyTableView indexPathForCell:cell];
    
    switch (flag) {
        case 11:
        {
            //做减法
            //先获取到当期行数据源内容，改变数据源内容，刷新表格
        PurchaseCarModel *model = infoArr[index.row];
        if (model.commodityNo.intValue > 1)
            {
            NSInteger num = model.commodityNo.integerValue;
            
            num--;
            model.commodityNo =[NSString stringWithFormat:@"%@",[NSNumber numberWithInteger:num]];
                [self updateShoppingCartActionRequest:model];

            }
        }
            break;
        case 12:
        {
            //做加法
        PurchaseCarModel *model = infoArr[index.row];
        
        NSInteger num = model.commodityNo.integerValue;
        
        num++;
        model.commodityNo =[NSString stringWithFormat:@"%@",[NSNumber numberWithInteger:num]];

            [self updateShoppingCartActionRequest:model];
        }
            break;
        default:
            break;
    }
    
        //刷新表格
    [_MyTableView reloadData];
    
        //计算总价
    [self totalPrice];
    
}

#pragma mark -- 计算价格
-(void)totalPrice
{
    [_arrModelData removeAllObjects];
    alTotallPrice = 0.00;
        //遍历整个数据源，然后判断如果是选中的商品，就计算价格（单价 * 商品数量）
    for ( int i =0; i<infoArr.count; i++)
        {

        PurchaseCarModel *model = [infoArr objectAtIndex:i];
        if (model.selectState)
            {
            
                    allPrice = allPrice + model.price.floatValue *[model.commodityNo intValue];

                [_arrModelData addObject:model];


            }
            else
            {
                [_arrModelData removeObject:model];
            }
        }
    
        //给总价文本赋值
    _allPriceLab.text = [NSString stringWithFormat:@"¥%.2f",allPrice];
    _labTotalNum.text = [NSString stringWithFormat:@"不含运费总计 %@ 件",[NSNumber numberWithInteger:_arrModelData.count]];


    NSLog(@"%f",allPrice);
    alTotallPrice = allPrice;
        //每次算完要重置为0，因为每次的都是全部循环算一遍
    allPrice = 0.0;
}








#pragma mark - network request settiement

-(void)getShoppingCartActionRequest
{
    [[LoadingView shareLoadingView] show];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",HostServer,getShoppingCartAction];
    
    ShareUserModel * shareUser  = [ShareUserModel shareUserModel];
    

    NSDictionary * params = @{
                              
                              @"currentNum":[NSString stringWithFormat:@"%@",[NSNumber numberWithInteger:currentNum]],
                              @"pageNum":[NSString stringWithFormat:@"%@",[NSNumber numberWithInteger:pageNum]],
                              @"loginName":[NSString stringWithFormat:@"%@",shareUser.user.phone],
                              @"sessionId":[NSString stringWithFormat:@"%@",shareUser.user.sessionId],
                              @"userId":[NSString stringWithFormat:@"%@",shareUser.user.user_id]
                              };
    
    
    
    
    
    
    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
     
     
         //               NSData *doubi = responseObject   ;
         //                   //     JSON格式的NSString转换成NSMutableDictionary
         //               NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //               NSError *err = nil;
         //               NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
     
     NSDictionary * dicRespon = responseObject;
     [self getShoppingCartActionSuccessWith:dicRespon];
     
     
     
     [[LoadingView shareLoadingView] dismissAnimated:YES];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
     [[LoadingView shareLoadingView] dismissAnimated:YES];
     [[NetWarningView sharedNetWarningView] show];  //警告网络异常
                                                    //              NSData *doubi = operation.error    ;
                                                    //                  //     JSON格式的NSString转换成NSMutableDictionary
                                                    //              NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
                                                    //
                                                    //              NSError *err = nil;
                                                    //              NSDictionary *dicRespon  = [NSJSONSerialization JSONObject9WithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
     NSLog(@"Error: %@", error);
     NSLog(@"请求出错了: - %@ \n%@",
           [error localizedDescription],
           [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
     }];
    
}

-(void)getShoppingCartActionSuccessWith :(NSDictionary *)dicRespon
{
    
    
    
    NSString * code = [dicRespon objectForKey:@"success"];
    if (code.integerValue ==1)
        {

            [infoArr removeAllObjects];
        
        
                NSArray *arrBussi = [dicRespon objectForKey:@"arr"];
                if (arrBussi && [arrBussi isKindOfClass:[arrBussi class]])
                    {
                        for (NSDictionary *dicTmp in arrBussi)
                      
                            {
                        NSError *error = nil;
                        PurchaseCarModel *modelTmp =
                        [MTLJSONAdapter modelOfClass:[PurchaseCarModel class] fromJSONDictionary:dicTmp error:&error];
                            

                            [modelTmp setValue:[NSNumber numberWithBool:NO] forKey:@"selectState"];
                        if(error == nil)
                            {
                                [infoArr addObject:modelTmp];
                            }
                        }

                    
                    [self.MyTableView reloadData];
                    
                    }
                [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        
        
        }
    else
        {
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        
        }
    
}


//


#pragma mark - network request updateShoppingCartAction

-(void)updateShoppingCartActionRequest:(PurchaseCarModel *)model

{
    [[LoadingView shareLoadingView] show];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",HostServer,updateShoppingCartAction];

    ShareUserModel * shareUser  = [ShareUserModel shareUserModel];


    NSDictionary * params = @{

                              @"commodityNo":[NSString stringWithFormat:@"%@",model.commodityNo],
                              @"id":[NSString stringWithFormat:@"%@",model.orderId],
                              @"loginName":[NSString stringWithFormat:@"%@",shareUser.user.phone],
                              @"sessionId":[NSString stringWithFormat:@"%@",shareUser.user.sessionId],
//                              @"userId":[NSString stringWithFormat:@"%@",shareUser.user.user_id]
                              };






    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {


         //               NSData *doubi = responseObject   ;
         //                   //     JSON格式的NSString转换成NSMutableDictionary
         //               NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //               NSError *err = nil;
         //               NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];

         NSDictionary * dicRespon = responseObject;
         [self updateShoppingCartActionSuccessWith:dicRespon];



         [[LoadingView shareLoadingView] dismissAnimated:YES];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[LoadingView shareLoadingView] dismissAnimated:YES];
         [[NetWarningView sharedNetWarningView] show];  //警告网络异常
         //              NSData *doubi = operation.error    ;
         //                  //     JSON格式的NSString转换成NSMutableDictionary
         //              NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //              NSError *err = nil;
         //              NSDictionary *dicRespon  = [NSJSONSerialization JSONObject9WithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
         NSLog(@"Error: %@", error);
         NSLog(@"请求出错了: - %@ \n%@",
               [error localizedDescription],
               [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
     }];

}

-(void)updateShoppingCartActionSuccessWith :(NSDictionary *)dicRespon
{



    NSString * code = [dicRespon objectForKey:@"success"];
    if (code.integerValue ==1)
    {


    
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];


    }
    else
    {
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];

    }

}




-(void)btnDeleteClick:(UIButton *)deleteClick
{

    for (int i = 0 ;i<infoArr.count;i++) {

        for (int j=0; j<_arrModelData.count;j++) {

        PurchaseCarModel * model = [infoArr objectAtIndex:i];

            PurchaseCarModel * modely = [infoArr objectAtIndex:j];


            if ( [modely.Purchaseid isEqualToString:model.Purchaseid])
            {
                NSLog(@"%@",modely.Purchaseid);
                NSLog(@"%@",model.Purchaseid);

                [infoArr removeObjectAtIndex:i];
                [_arrModelData removeObjectAtIndex:j];
            }

        }

    }


    _labTotalNum.text = [NSString stringWithFormat:@"不含运费总计 %@ 件",[NSNumber numberWithInteger:_arrModelData.count]];


    [self.MyTableView reloadData];


}
-(void)btnSettlementAction:(UIButton *)sender
{

    if ([_arrModelData count]!=0) {
        SettlementViewController * settt =[[SettlementViewController alloc] initWithNibName:@"SettlementViewController" bundle:nil];

        settt.strYiJianGouMai = @"SettlementViewController";
        settt.arrData = self.arrModelData;
        settt.allTotalprice  =[NSString stringWithFormat:@"%.2f",alTotallPrice];

        [self presentViewController:settt animated:YES completion:0];

    }
    else{

        [[MainTabbarController ShareTabBarController] showMessage:@"请选择需要商品"];
    }
}




@end
